package com.linxz.ui;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.util.DisplayMetrics;
import android.util.LruCache;
import android.util.TypedValue;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.linxz.framework.protocol.image.ImageHelper;
import com.linxz.ui.divider.BaseDecoration;
import com.linxz.ui.divider.SpaceItemDecoration;
import com.linxz.ui.widgets.HorizontalLayout;

import java.io.File;

/**
 * @author Linxz
 * 创建日期：2019年04月24日 10:51
 * version：1.0.0
 * 描述：
 */
public class GuiHelper {

    /**glide加载图片*/
    public static void loadImage(Context context, String url, ImageView imageView){
        ImageHelper.imageNet(context,url,imageView);
    }

    public static void loadImage(Context context, File file, ImageView imageView){
        ImageHelper.imageLocal(context,file,imageView);
    }

    public static void loadLocalImage(Context context, String filePath, ImageView imageView){
        ImageHelper.imageLocal(context,filePath,imageView);
    }


    /**
     * 带圆角的图片加载,会有加载不出的问题
     * @deprecated {@link GuiHelper#loadImageWithCorner}
     * */
    public static void loadImage(Context context,String url,float radius,ImageView imageView){
       //ImageHelper.imageNet(context,url,imageView);
        ImageHelper.displayImageForView(imageView,url);
    }



    /**
     * 只加载顶部圆角
     * */
    public static void loadImageWithCorner(Context context,String url,ImageView imageView,float radius){
       ImageHelper.imageLoadWithCorner(context,url,imageView,radius);
    }

    /**加载部分方向圆角图片*/
    public static void loadImageWithCorner(Context mContext,
                                            String url,
                                            ImageView view,
                                            float radius,
                                            boolean leftTop,
                                            boolean rightTop,
                                            boolean leftBottom,
                                            boolean rightBottom) {
        ImageHelper.imageLoadWithCorner(mContext,url,view,radius,leftTop,rightTop,leftBottom,rightBottom);
    }


    /**
     * RecycleView分割线
     *
     * */
    public static void initRecycleView(Context context, RecyclerView mRecyclerView, BaseQuickAdapter adapter, int height){
        int spacingInPixels = dip2px(context, height);
        mRecyclerView.addItemDecoration(BaseDecoration.create(ContextCompat.getColor(context, R.color.pg_bg),spacingInPixels));
        mRecyclerView.setLayoutManager(new LinearLayoutManager(context));
        mRecyclerView.setAdapter(adapter);
    }

    /**
     * RecycleView垂直分割线
     *
     * */
    public static void initRecycleViewForVerticalDivider(Context context, RecyclerView mRecyclerView, BaseQuickAdapter adapter, int height){
        int spacingInPixels = dip2px(context, height);
        mRecyclerView.addItemDecoration(new SpaceItemDecoration(spacingInPixels,SpaceItemDecoration.HORIZONTAL_LIST));
        mRecyclerView.setLayoutManager(new HorizontalLayout(context));
        mRecyclerView.setAdapter(adapter);
    }


    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }





    /**
     * 计算状态栏高度（包括刘海屏高度）
     * @return 状态栏高度
     */
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        try {
            int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId > 0) {
                result = Math.round(context.getResources().getDimensionPixelSize(resourceId) * Resources.getSystem().getDisplayMetrics().density / context.getResources().getDisplayMetrics().density);
            }
        } catch (Resources.NotFoundException ignored) {
            return 0;
        }
        return result;
    }



    /**
     * 设置升级内容属性
     */
    public static TextView setUpdateContentText(Context context, String string, int color) {
        TextView textView = new TextView(context);
        textView.setText(string);
        textView.setTextColor(color);
        textView.setPadding(40, 10, 40, 10);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
        return textView;
    }


    /**
     * 获取设备宽度(平板高度)
     */
    public static int getDeviceWidth(Context context) {
        final Resources resources =context.getResources();
        Configuration mConfiguration = resources.getConfiguration();
        final DisplayMetrics dm = resources.getDisplayMetrics();
        int ori = mConfiguration.orientation;
        if (ori == Configuration.ORIENTATION_LANDSCAPE) {
            return dm.heightPixels;
        } else{
            return dm.widthPixels;
        }
    }


    /**
     * 获取设备宽度(平板高度)
     */
    public static int getDeviceHeight(Context context) {
        final Resources resources =context.getResources();
        Configuration mConfiguration = resources.getConfiguration();
        final DisplayMetrics dm = resources.getDisplayMetrics();
        int ori = mConfiguration.orientation;
        if (ori == Configuration.ORIENTATION_LANDSCAPE) {
            return dm.widthPixels;
        } else{
            return dm.heightPixels;
        }
    }

    public static int getDimensionPixelSize(Context context,int res){
        return context.getResources().getDimensionPixelSize(res);
    }


    /**
     * TextView设置DrawableLeft
     * */
    public static void setDrawableLft(TextView textView,int drawable){
        Drawable leftDrawable=textView.getContext().getResources().getDrawable(drawable);
        leftDrawable.setBounds(0, 0, leftDrawable.getMinimumWidth(), leftDrawable.getMinimumHeight());
        textView.setCompoundDrawables(leftDrawable, null, null, null);
    }

    /**
     * 图标旋转
     * */
    /**
     * 旋转箭头
     * @param isUp:箭头方向
     * @param iv:
     * */
    public static void rotateArrowAnimation(boolean isUp,ImageView iv){
        if (iv == null) return;
        float fromDegrees=180f;
        if (!isUp){
            fromDegrees=-180f;
        }
        RotateAnimation animation = new RotateAnimation(fromDegrees, 0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        animation.setDuration(200);
        animation.setFillAfter(true);
        iv.startAnimation(animation);
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dp2px(float dpValue) {
        return (int) (0.5f + dpValue * Resources.getSystem().getDisplayMetrics().density);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static float px2dp(float pxValue) {
        return (pxValue / Resources.getSystem().getDisplayMetrics().density);
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(float dpValue) {
        float density = Resources.getSystem().getDisplayMetrics().density;
        return (int) (0.5f + dpValue * density);
    }


    public static Bitmap shotRecyclerView(RecyclerView view) {
        RecyclerView.Adapter adapter = view.getAdapter();
        Bitmap bigBitmap = null;
        if (adapter != null) {
            int size = adapter.getItemCount();
            int height = 0;
            Paint paint = new Paint();
            int iHeight = 0;
            final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
            // Use 1/8th of the available memory for this memory cache.
            final int cacheSize = maxMemory / 8;
            //这个地方用LruCache显得高大上，实际上用个List也是可以的
            LruCache<String, Bitmap> bitmapCache = new LruCache<>(cacheSize);
            for (int i = 0; i < size; i++) {
                RecyclerView.ViewHolder holder = adapter.createViewHolder(view, adapter.getItemViewType(i));
                adapter.onBindViewHolder(holder, i);
                holder.itemView.measure(
                        View.MeasureSpec.makeMeasureSpec(view.getWidth(), View.MeasureSpec.EXACTLY),
                        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
                holder.itemView.layout(0, 0, holder.itemView.getMeasuredWidth(),
                        holder.itemView.getMeasuredHeight());
                holder.itemView.setDrawingCacheEnabled(true);
                holder.itemView.buildDrawingCache();
                Bitmap drawingCache = holder.itemView.getDrawingCache();
                if (drawingCache != null) {
                    bitmapCache.put(String.valueOf(i), drawingCache);
                }
                height += holder.itemView.getMeasuredHeight();
            }
            // 这个地方容易出现OOM，关键是要看截取RecyclerView的展开的宽高
            bigBitmap = Bitmap.createBitmap(view.getMeasuredWidth(), height, Bitmap.Config.ARGB_8888);
            Canvas bigCanvas = new Canvas(bigBitmap);
            Drawable lBackground = view.getBackground();
            //先画RecyclerView的背景色
            if (lBackground instanceof ColorDrawable) {
                ColorDrawable lColorDrawable = (ColorDrawable) lBackground;
                int lColor = lColorDrawable.getColor();
                bigCanvas.drawColor(lColor);
            }
            for (int i = 0; i < size; i++) {
                Bitmap bitmap = bitmapCache.get(String.valueOf(i));
                bigCanvas.drawBitmap(bitmap, 0f, iHeight, paint);
                iHeight += bitmap.getHeight();
                bitmap.recycle();
            }
        }
        return bigBitmap;
    }

    /**
     * 隐藏软键盘
     * @param activity
     */
    public static void hideKeyboard(Activity activity) {
        if (activity != null) {
            InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm.isActive()) {
                imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
            }
        }
    }

    /**
     * 显示软键盘
     * @param activity
     */
    public static void showKeyboard(Activity activity) {
        if (activity != null) {
            InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            if (!imm.isActive()) {
                imm.showSoftInputFromInputMethod(activity.getCurrentFocus().getWindowToken(), 0);
            }
        }
    }


    public static Activity getActivity(Context context){
        if (context instanceof Activity){
            return ((Activity) context);
        }else if (context instanceof ContextWrapper){
            ContextWrapper wrapper = (ContextWrapper) context;
            return getActivity(wrapper.getBaseContext());
        }else{
            Toast.makeText(context,"关闭Activity失败",Toast.LENGTH_SHORT).show();
            return null;
        }
    }


    public static void copy(Activity activity,String content){
        ClipboardManager cm = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData mClipData = ClipData.newPlainText("Label", content);
        if (cm != null) {
            cm.setPrimaryClip(mClipData);
            Toast.makeText(activity,"已复制",Toast.LENGTH_SHORT).show();
        }
    }


    public static Bitmap getViewBitmap(View view) {
        Bitmap bitmap;
        if (view.getWidth() > 0 && view.getHeight() > 0)
            bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
        else if (view.getMeasuredWidth() > 0 && view.getMeasuredHeight() > 0)
            bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
        else
            bitmap = Bitmap.createBitmap(getDeviceWidth(view.getContext()), getDeviceHeight(view.getContext()) * 2, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        view.draw(canvas);
        return bitmap;
    }


}
